/* Copyright (c) 2004-2023 Peigen.info. All rights reserved. */
package info.peigen.hotpot.manage.core.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceInvoke;
import info.peigen.hotpot.manage.core.cache.ManageCache;
import info.peigen.hotpot.manage.core.service.facade.AuthServiceFacade;
import info.peigen.hotpot.manage.core.service.order.LoginOrder;
import info.peigen.hotpot.manage.core.service.result.AuthPicValidCodeResult;
import info.peigen.hotpot.manage.core.service.result.LoginResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

/**
 * <b>(AuthService)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2024/6/11
 */
@Component
public class AuthService extends AbstractHotpotManageService implements AuthServiceFacade {
    @Inject
    ManageCache cache;

    @Override
    public LoginResult login(LoginOrder order) {
        ProcessorServiceContext serviceContext = ProcessorServiceContext.builder().order(order)
                .result(new LoginResult()).build();
        execute(serviceContext, new ProcessorServiceInvoke() {
            @Override
            public void addPreProcessor(ProcessorServiceContext serviceContext) {
                serviceContext.addProcessors(authLoginCheckProcessor, authCheckValidCodeProcessor);
            }

            @Override
            public void addProcessor(ProcessorServiceContext serviceContext) {
                serviceContext.addProcessors(userActiveProcessor, roleActiveProcessor, positionActiveProcessor, organizationActiveProcessor);
            }

            @Override
            public void addPostProcessor(ProcessorServiceContext serviceContext) {
                serviceContext.addProcessors(loginTokenProcessor, loginResultProcessor);
            }
        });

        return (LoginResult) serviceContext.getResult();
    }

    @Override
    public AuthPicValidCodeResult getPicCaptcha() {
        // 生成验证码，随机4位字符
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(100, 38, 4, 10);
        // 定义返回结果
        AuthPicValidCodeResult authPicValidCodeResult = new AuthPicValidCodeResult();
        // 获取验证码的值
        String validCode = circleCaptcha.getCode();
        // 获取验证码的base64
        String validCodeBase64 = circleCaptcha.getImageBase64Data();
        // 生成请求号
        String validCodeReqNo = IdUtil.getSnowflakeNextIdStr();
        // 将base64返回前端
        authPicValidCodeResult.setValidCodeBase64(validCodeBase64);
        // 将请求号返回前端
        authPicValidCodeResult.setValidCodeReqNo(validCodeReqNo);
        // 将请求号作为key，验证码的值作为value放到缓存中，用于校验，5分钟有效
        cache.put(ManageCache.AUTH_VALID_CODE_CACHE_KEY + validCodeReqNo, validCode);
        return authPicValidCodeResult;
    }
}
